package net.jueb.httpFileServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.File;

import org.apache.log4j.Logger;


public class HttpFileServer {
	private static Logger log=Logger.getLogger(HttpFileServer.class);
	/**
	 * 根目录
	 */
	private  String rootDir;
	private int port;
	
	public HttpFileServer(String rootDir,int port) {
		this.rootDir=rootDir;
		this.port=port;
	}
	
	public void start()
	{
		File f=new File(rootDir);
		if(!f.isDirectory())
		{
			log.error("根目录不存在!");
			return ;
		}
		if(port<0)
		{
			log.error("端口错误");
			return ;
		}
		NioEventLoopGroup boss=new NioEventLoopGroup();
		NioEventLoopGroup worker=new NioEventLoopGroup();
		ServerBootstrap sbt=new ServerBootstrap();
		sbt.group(boss, worker);
		sbt.channel(NioServerSocketChannel.class);
		sbt.option(ChannelOption.SO_BACKLOG,Integer.MAX_VALUE);
		sbt.option(ChannelOption.SO_KEEPALIVE, true);
		sbt.handler(new LoggingHandler(LogLevel.DEBUG));
		sbt.childHandler(new HttpFileServerInitializer(rootDir));
		try {
			Channel channel=sbt.bind(port).sync().channel();
			log.info("http文件服务器启动成功："+channel.localAddress()+",启动根目录："+rootDir);
			channel.closeFuture().sync();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		int port=8080;
		String dir=new File(".").getAbsolutePath();
		dir=dir.substring(0,dir.length()-1);
		System.out.println(dir);
		if(args.length>=1)
		{
			port=Integer.parseInt(args[0]);
		}
		if(args.length>=2)
		{
			dir=args[1];
		}
//		new HttpFileServer(dir, port).start();
		new HttpFileServer("e:/", port).start();
	}
}
